/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package py.com.webdav.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JasperManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;

/**
 *
 * @author markos
 */
public class DAVReporter {

    private Connection conn;
    private Context context;

    private void getConnection() throws SQLException, NamingException {
        context = new InitialContext();
        //Context contexto = (Context) context.lookup("java:comp/env");
        //DataSource ds = (DataSource) context.lookup("jdbc/dav");
        try {
            Class.forName("org.postgresql.Driver");
            // Get a Connection to the database
            conn = DriverManager.getConnection("jdbc:postgresql://localhost/dav", "postgres", "123456");
        } catch (Exception e) {
        }

        if (conn != null) {
            System.out.println("No soy null markos.");
        }
    }

    private void closeConnection() throws SQLException {
        conn.close();
    }

    public void getReport(String sNameReport, Map parameters, ServletContext sc, String format)
            throws Exception {
        String realPathXml = sc.getRealPath("reportes/");
        getConnection();
        try {
            System.out.println("path : " + realPathXml + "/" + sNameReport);
            //JasperReport jasperReport = (JasperReport) JRLoader.loadObject(realPathXml + "/" + sNameReport);
            JasperReport jasperReport = JasperManager.compileReport(realPathXml + "/" + "denuncias_dav.jrxml");

            byte[] pdf = null;

            pdf = JasperRunManager.runReportToPdf(jasperReport, parameters, conn);
            FacesContext faces = FacesContext.getCurrentInstance();
            HttpServletResponse response =
                    (HttpServletResponse) faces.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.setContentLength(pdf.length);
            response.setHeader("Content-disposition", "inline; filename=\"Denuncia.pdf\"");

            ServletOutputStream out = response.getOutputStream();
            out.write(pdf);

            faces.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            closeConnection();
        }
    }
}
